/*
Copyright 2005-2014 CP Fricano - All Rights Reserved

This software and source code is licensed under the Apache
License, Version 2.0. You may not use this software or source
code except in compliance with the License.  You may obtain a
copy of the License at: http://www.apache.org/licenses/LICENSE-2.0.
Use and distributed under this License is on an "as is" basis,
without expressed or implied warranties or conditions of any kind.
See the License for the specific language governing permissions and
limitations.
 */

package com.fricano.java42.instructional.example.swing;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JFrame;

public class J42JFrame_01 extends JFrame {

    private static final long serialVersionUID = -42L;
    private String            title            = null;

    @Override
    public void setTitle(final String string) {
        if (string != null && !(string.trim().equals(""))) {
            title = string.trim();
            final Font f = getFont();
            final FontMetrics fm = getFontMetrics(f);
            final int x = fm.stringWidth(title);
            final int y = fm.stringWidth(" ");
            final int z = (getWidth() / 2) - (x / 2);
            final int w = z / y;
            String pad = "";
            if (w > 1) {
                pad = String.format("%" + w + "s", pad);
            }
            super.setTitle(pad + title);
        }
    }

    public J42JFrame_01() {
        super();
        setFont(new Font("System", Font.PLAIN, 14));
        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentShown(final ComponentEvent e) {
                setTitle(title);
            }

            @Override
            public void componentResized(final ComponentEvent e) {
                setTitle(title);
            }
        });
    }

    public J42JFrame_01(final String s) {
        this();
        setTitle(s);
    }

}
